/*
 * @Author: wcx 1055127249@qq.com
 * @Date: 2025-01-06 10:30:01
 * @LastEditors: wcx 1055127249@qq.com
 * @LastEditTime: 2025-01-07 11:28:14
 * @FilePath: \my-project\src\api\request.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import axios from 'axios'

const service = axios.create({
  baseURL: '',
  timeout: 5000
})

function requestHandle (config) {
  if (config.url.indexOf('/login') === -1) {
    config.headers.Authorization = localStorage.getItem('token')
  }
  return config
}

function responseHandle ({ data, config }) {
  var { url } = config
  if (data.code === 200) {
    if (url.includes('/logout')) {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
    } else if (url.includes('/login')) {
      localStorage.setItem('token', data.token)
      localStorage.setItem('userInfo', data.userInfo)
    }
    return data
  } else {
    return Promise.reject(new Error(data.msg))
  }
}

const errorHandle = error => {
  Promise.reject(error)
}

service.interceptors.request.use(requestHandle, errorHandle)
service.interceptors.response.use(responseHandle, errorHandle)

export default service